#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import json
import stat
import re

from ndmp.comm.param_base import ParamBase
from ndmp.comm.log import log
from common.const import SubJobStatusEnum, RepositoryDataTypeEnum, SubJobPriorityEnum, ParamConstant
from ndmp.comm.utils import get_env_in_variable
from common.parse_parafile import ParamFileUtil
from common.cleaner import clear
from ndmp.comm.const import SubJobType, NDMPCode, BackupType


class IndexParam(ParamBase):
    def __init__(self, req_id):
        super().__init__(req_id)
        self._application: dict = dict()
        self._auth_flag = True
        self.parse_param()

    def parse_param(self):
        try:
            self._param = ParamFileUtil.parse_param_file(self.req_id)
        except Exception as err:
            raise Exception(f"Failed to parse job param file for {err}") from err
    
    def get_copy_id(self):
        try:
            copy_id = self._param.get("job", {}).get("copies", [])[-1].get("extendInfo", {}).get("copy_id")
        except AttributeError as err:
            log.error(f"get ParamError, err:{err}")
            return ""
        return copy_id

    def get_curr_repository(self, repository_type):
        try:
            copies = self._param.get("job", {}).get("copies", [])
            for copy in copies:
                path = self.get_repository_path(copy, repository_type)
                if path:
                    return path
        except AttributeError as err:
            log.error(f"get ParamError, err:{err}")
        return ""

    def get_repository_path(self, copy, repository_type):
        try:
            repositories = copy.get("repositories")
            for repository in repositories:
                if (repository.get("repositoryType") == repository_type and
                    repository.get("extendInfo").get("isCurrentCopyRepo") is True):
                    return repository.get("path")[0]
        except AttributeError as err:
            log.error(f"get ParamError, err:{err}")
        return ""
    
    def get_last_copy_id(self):
        try:
            pre_copy_id = self._param.get("job", {}).get("jobParam").get("preCopyId")
            if pre_copy_id is None or pre_copy_id == "":
                copy_id = self._param.get("job", {}).get("copies", [])[-1].get("extendInfo", {}).get("copy_id")
                return copy_id
            return pre_copy_id
        except AttributeError as err:
            log.error(f"get ParamError, err:{err}")
        return ""        

    def get_repository(self, repository_type):
        repositories = self._param.get("job", {}).get("repositories", [])
        for repository in repositories:
            if repository['repositoryType'] == repository_type:
                return repository
        return {}

    def get_index_repository_path(self, repository_type):
        return self.get_repository(repository_type).get("path", [])[0]
    
    def clear(self):
        """
        清理敏感信息
        :return:
        """
        clear(self.get_src_auth())
        clear(self.get_dst_auth())
        clear(self.get_src_pwd())
        clear(self.get_dst_pwd())
    

    def get_src_ip(self):
        src_ip = self._param.get("job", {}).get("targetEnv", {}).get("endpoint")
        return src_ip

    def get_dst_ip(self):
        dst_ip = self._param.get("job", {}).get("targetEnv", {}).get("extendInfo", {}).get("serviceIp")
        return dst_ip

    def get_src_auth(self):
        """
        获取本端用户名
        """
        src_auth = get_env_in_variable(f"job_targetEnv_auth_extendInfo_authKey_{self.req_id}")
        return src_auth

    def get_dst_auth(self):
        """
        获取远端端用户名
        """
        dst_auth = get_env_in_variable(f"job_targetEnv_auth_authKey_{self.req_id}")
        return dst_auth

    def get_src_pwd(self):
        """
        获取本端用户密码
        """
        src_pwd = get_env_in_variable(f"job_targetEnv_auth_extendInfo_authPwd_{self.req_id}")
        return src_pwd

    def get_dst_pwd(self):
        """
        获取远端用户密码
        """
        dst_pwd = get_env_in_variable(f"job_targetEnv_auth_authPwd_{self.req_id}")
        return dst_pwd

    def get_src_path(self):
        src_path = json.loads(self._application.get("extendInfo", {}).get("ndmpSrc")).get("path")
        return src_path

    def get_dst_path(self):
        dst_path = json.loads(self._application.get("extendInfo", {}).get("ndmpDst")).get("path")
        return dst_path
